//
//  HJMineControler.m
//  BaoDian
//
//  Created by mac on 2024/7/17.
//

#import "TJPersonalCenterControler.h"
#import "TJIconTitleCellButton.h"
#import "TJMineInfoItem.h"
#import "TJMineItem.h"
#import "TJButton.h"
#import "TJUIAlertController.h"
#import <DouyinOpenSDK/DouyinOpenSDKAuth.h>
#import "TJUserInfoController.h"
 

@interface TJPersonalCenterControler ()


@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, weak) UILabel *douYinNameLabel;
@property (nonatomic, weak) UILabel *merchantNameLabel;
@property (nonatomic, weak) UILabel *nicknameLabel;
@property (nonatomic, weak) UIButton *modifyButton;


@end

@implementation TJPersonalCenterControler

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIScrollView *scrollView = [UIScrollView addToView:self.view];
    scrollView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - TabBarHeight);
    CGSize contentSize = scrollView.bounds.size;
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    scrollView.contentSize = contentSize;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.alwaysBounceVertical = YES;
    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    UIView *contentView = [[UIView alloc] init].addTo(scrollView);
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(contentSize.width);
        make.height.offset(contentSize.height);
    }];
    
    UIView *infoView = [UIView addToView:contentView];
    infoView.backgroundColor = UIColor.tj_1E1F23Color;
    infoView.addCornerRadius(12);
    
    UIImageView *avatarImageView = [UIImageView addToView:contentView];
    avatarImageView.addCornerRadius(8);
    [avatarImageView tj_setImageWithURL:TJUserInfo.avatar.URL placeholderImage:[UIImage imageNamed:defaultAvatarName]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.width.height.offset(60);
        make.top.equalTo(infoView).offset(-9);
    }];
    
    UILabel *nicknameLabel = [UILabel lableWithSuperView:infoView font:UIFontSemiboldMake(18) color:UIColor.whiteColor title:TJUserInfo.nickname textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(14);
        make.left.equalTo(avatarImageView.mas_right).offset(12);
        make.right.mas_lessThanOrEqualTo(-100);
    }];
    
    TJButton *infoButton = [TJButton buttonWithSuperView:infoView font:UIFontMake(12) color:UIColor.tj_8D9298Color title:@"个人信息"];
    [infoButton setImagePosition:QMUIButtonImagePositionLeft];
    [infoButton addTarget:self action:@selector(didClickInfoButton) forControlEvents:UIControlEventTouchUpInside];
    [infoButton setImage:[UIImage imageNamed:@"info_icon"] forState:UIControlStateNormal];
    infoButton.layer.borderColor = UIColor.tj_8D9298Color.CGColor;
    infoButton.layer.borderWidth = 0.5;
    infoButton.addCornerRadius(6);
    [infoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(16);
        make.height.offset(HZoom(24));
        make.top.offset(15);
        make.width.offset(HZoom(72));
    }];
    
    UILabel *merchantNameLabel = [UILabel lableWithSuperView:infoView font:UIFontMake(14) color:UIColor.tj_8D9298Color title:@"所属商家: --" textAlignment:NSTextAlignmentLeft];
    [merchantNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(avatarImageView.mas_bottom).offset(18);
        make.left.equalTo(avatarImageView);
        make.right.mas_lessThanOrEqualTo(-16);
        make.height.offset(20);
    }];
    
    UILabel *douYinNameLabel = [UILabel lableWithSuperView:infoView font:UIFontMake(14) color:UIColor.tj_8D9298Color title:@"抖音信息: --" textAlignment:NSTextAlignmentLeft];
    [douYinNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(merchantNameLabel.mas_bottom).offset(8);
        make.left.equalTo(avatarImageView);
        make.right.mas_lessThanOrEqualTo(-72);
    }];
 
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.offset(KNavBarHight + 10);
        make.bottom.equalTo(douYinNameLabel.mas_bottom).offset(16);
    }];
    
    TJButton *modifyButton = [TJButton buttonWithSuperView:contentView font:UIFontMediumMake(14) color:UIColorMake(0x2978F0) title:@"修改授权"];
    [modifyButton addTarget:self action:@selector(didClickModifyButton) forControlEvents:UIControlEventTouchUpInside];
    [modifyButton sizeToFit];
    [modifyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(douYinNameLabel.mas_right).offset(3);
        make.centerY.equalTo(douYinNameLabel);
        make.width.offset(modifyButton.tj_width);
        make.height.offset(20);
    }];
    
    UIImageView *taskImageView = [UIImageView addToView:contentView];
    taskImageView.image = [UIImage imageNamed:@"taskBackground"];
    taskImageView.userInteractionEnabled = YES;
    taskImageView.contentMode = UIViewContentModeScaleAspectFill;
    [taskImageView addTapGesturesWithTarget:self action:@selector(didClickClockInButton)];
    [taskImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.height.offset(76);
        make.top.equalTo(infoView.mas_bottom).inset(24);
    }];
    
    UILabel *taskLabel = [UILabel lableWithSuperView:taskImageView font:UIFontSemiboldMake(16) color:UIColor.whiteColor title:@"任务打卡" textAlignment:NSTextAlignmentLeft];
    [taskLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(16);
        make.left.offset(27);
    }];
    
    UILabel *taskEnglishLabel = [UILabel lableWithSuperView:taskImageView font:UIFontMediumMake(13) color:UIColor.whiteColor title:@"TASK PUNCH" textAlignment:NSTextAlignmentLeft];
    taskEnglishLabel.alpha = 0.4;
    [taskEnglishLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(16);
        make.left.equalTo(taskLabel);
    }];
    
    UIButton *clockInButton = [UIButton buttonWithSuperView:taskImageView font:UIFontMake(12) color:UIColorMake(0x222222) title:@"去打卡"];
    clockInButton.addCornerRadius(13);
    [clockInButton addTarget:self action:@selector(didClickClockInButton) forControlEvents:UIControlEventTouchUpInside];
    clockInButton.backgroundColor = UIColorMake(0xFFE7B2);
    [clockInButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.inset(16);
        make.width.offset(60);
        make.height.offset(26);
    }];
    
    TJIconTitleCellButton *clockInRecordButton = [TJIconTitleCellButton addToView:contentView];
    clockInRecordButton.backgroundColor = UIColor.tj_1E1F23Color;
    [clockInRecordButton addTarget:self action:@selector(didClickListButton:) forControlEvents:UIControlEventTouchUpInside];
    clockInRecordButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"打卡记录";
        model.identifier = @"clockInRecord";
        model.iconName = @"clockInRecord_icon";
        model.showArrow = YES;
    }];
    clockInRecordButton.bounds = CGRectMake(0, 0, KScreenWidth - 32, 56);
    [clockInRecordButton addRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:12];
    [clockInRecordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.equalTo(taskImageView.mas_bottom).inset(16);
        make.height.offset(56);
    }];
    
    TJIconTitleCellButton *versionButton = [TJIconTitleCellButton addToView:contentView];
    versionButton.backgroundColor = UIColor.tj_1E1F23Color;
    versionButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"APP版本";
        model.identifier = @"version";
        model.iconName = @"version_icon";
        model.showArrow = NO;
    }];
    versionButton.bounds = CGRectMake(0, 0, KScreenWidth - 32, 56);
    [versionButton addRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight radius:12];
    [versionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.equalTo(clockInRecordButton.mas_bottom);
        make.height.offset(56);
    }];
    
    UILabel *versionValueLabel = [UILabel lableWithSuperView:versionButton font:UIFontMake(12) color:UIColor.tj_8D9298Color title:[NSString stringWithFormat:@"当前版本v%@", getAppVersion()] textAlignment:NSTextAlignmentLeft];
    [versionValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(16);
        make.centerY.offset(0);
    }];
    
    TJIconTitleCellButton *logoutButton = [TJIconTitleCellButton addToView:contentView];
    logoutButton.backgroundColor = UIColor.tj_1E1F23Color;
    logoutButton.addCornerRadius(12);
    [logoutButton addTarget:self action:@selector(didClickListButton:) forControlEvents:UIControlEventTouchUpInside];
    logoutButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"退出登录";
        model.identifier = @"logout";
        model.iconName = @"logout_icon";
        model.showArrow = YES;
    }];
    [logoutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.equalTo(versionButton.mas_bottom).inset(10);
        make.height.offset(56);
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    contentSize = CGSizeMake(contentSize.width, logoutButton.tj_MaxY + 10);
    scrollView.contentSize = contentSize;
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(contentSize.height);
    }];
    
    _avatarImageView = avatarImageView;
    _douYinNameLabel = douYinNameLabel;
    _merchantNameLabel = merchantNameLabel;
    _nicknameLabel = nicknameLabel;
    _modifyButton = modifyButton;

    [self reloadData];
}

- (void)reloadData {
    dispatch_async_sql_queue(^{
        TJUserModel *userModel = [TJUserModel currentAccountModel];
        dispatch_async_main_queue(^{
            
            [self.avatarImageView tj_setImageWithURL:userModel.avatar.URL placeholderImage:[UIImage imageNamed:defaultAvatarName]];
            self.nicknameLabel.text = userModel.realName;
            self.merchantNameLabel.text = [NSString stringWithFormat:@"所属商家: %@", userModel.supplierName];

            if ([userModel.openId isKindOfClass:NSString.class] && !isEmptyString(userModel.openId)) {//已经授权
                self.douYinNameLabel.text = [NSString stringWithFormat:@"抖音信息: %@", userModel.nickname];
                [self.modifyButton setTitle:@"修改授权" forState:UIControlStateNormal];
            } else {//未授权
                self.douYinNameLabel.text = @"抖音信息: --";
                [self.modifyButton setTitle:@"去授权" forState:UIControlStateNormal];
            }
            [self.modifyButton sizeToFit];
            [self.modifyButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.offset(self.modifyButton.tj_width);
            }];
        });
    });
}


- (void)didClickListButton:(TJIconTitleCellButton *)button {
    
    TJCellModel *model = button.model;
    
    if ([model.identifier isEqualToString:@"logout"]) {
        TJUIAlertController *alert = [TJUIAlertController alertControllerWithTitle:nil message:@"您是否确认退出该账号" preferredStyle:TJUIAlertControllerStyleActionSheet];
        [alert addAction:[TJUIAlertAction actionWithTitle:@"确认" style:TJUIAlertActionStyleDefault handler:^(TJUIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:logoutNotification object:nil];
        }]];
        [alert addAction:[TJUIAlertAction actionWithTitle:@"取消" style:TJUIAlertActionStyleCancel handler:^(TJUIAlertAction * _Nonnull action) {
            
        }]];
        [alert showInViewController:self];
        return;
    }
    
    if ([model.identifier isEqualToString:@"clockInRecord"]) {
        [self.navigationController pushViewControllerWithName:@"TJClockInRecardController"];
        return;
    }
 }

- (void)didClickClockInButton {
    [self.navigationController pushViewControllerWithName:@"TJTaskListController"];
}

- (void)didClickModifyButton {
     DouyinOpenSDKAuthRequest *request = [[DouyinOpenSDKAuthRequest alloc] init];
     request.permissions = [NSOrderedSet orderedSetWithObject:@"user_info"];

      [request sendAuthRequestViewController:self completeBlock:^(DouyinOpenSDKAuthResponse * _Nonnull resp) {
        if (resp.errCode == 0) {
            [TJMinePresent douYinLicenseWithCode:resp.code complete:^(TJUserModel * _Nullable model, NSError * _Nullable error) {
                if (error) {
                    return;
                }
                
                [self reloadData];
            }];
         } else {
             [TJHUD showMessage:@"授权失败"];
         }
      }];
}
 
- (void)didClickInfoButton {
    TJUserInfoController *userInfoController = [[TJUserInfoController alloc] init];
    [userInfoController setUpdateInfoBlock:^(NSInteger type, id  _Nonnull value) {
        if (type == 1) {
            [self.avatarImageView tj_setImageWithURL:[value URL] placeholderImage:self.avatarImageView.image];
        } else if (type == 2) {
            self.nicknameLabel.text = value;
        }
    }];
    [self.navigationController pushViewController:userInfoController];
}

- (BOOL)hiddenNavigationBar {
    return YES;
}
 
- (UIImage *)topBackgroundImage {
    return [UIImage imageNamed:@"mine_bg"];
}

@end
